package web.department;

import bean.Department;
import bean.Video;
import com.alibaba.fastjson.JSON;
import entity.DepartmentEntity;
import entity.StaffEntity;
import entity.VideoEntity;
import util.FANREN;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "DepartmentDelete",urlPatterns = "/dao/update/departmentDelete")
public class DepartmentDelete extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String jsonString = FANREN.getJson(request);
        System.out.println(jsonString);
        EntityManager em = (EntityManager) request.getAttribute("_entity.Manager");
        Department department = JSON.parseObject(jsonString,Department.class);
        DepartmentEntity departmentEntity = em.find(DepartmentEntity.class,Integer.parseInt(department.getDid()));

        Query query = em.createQuery("select v from StaffEntity v");
        List<StaffEntity> list = query.getResultList();
        for (int i=0; i<list.size(); i++) {
            if((list.get(i).getDid().getDid()+"").equals(departmentEntity.getDid()+""))
                throw new RuntimeException();
        }
        if(departmentEntity!=null)
            em.remove(departmentEntity);
    }
}
